<?php
	//使用Mysql来改进原有的简单验证机制
	
	$username = $_POST['username'];
	$password = $_POST['password'];

	if ((!isset($username)) || (!isset($password))) {
?>

	<h1>Please Log In</h1>
	<p>This page is secret!</p>
	<form action="secretdb.php" method="post">
	<p>用户名:<input type="text" name="username" /></p>
	<p>密码:<input type="password" name="password" /></p>
	<p><input type="submit" name="submit" value="登录" /></p>
	</form>

<?php
	}
	else {
		//connect to mysql
		// $mysql = mysql_connect("localhost", "webauth", "webauth", "auth");
		$db = new mysqli("localhost", "webauth", "webauth", "authorized_user");
		if (mysqli_connect_errno()) {
			echo "Cannot connect to database!";
			exit();
		}
		/*if (!$mysql) {
			echo "Cannot connect to database!";
			exit();
		}*/
		//query to the database to see if there is a record which matches
		$query = "select count(*) from authorized_user where name = '".$username."' and password = '".$password."'";

		// $result = mysqli_query($mysql, $query);
		$result = $db->query($query);
		if (!$result) {
			echo "Cannot run query!";
			exit();
		}

		// $row = mysqli_fetch_row($result);
		$row = $result->fetch_row;
		$count = $row[0];

		if ($count>0) {
			echo "<h1>Here it is !</h1>
			<p>I bet you are glad you can see this secret page.</p>";
		} else {
			echo "<h1>Go Away!</h1>
			<p>You are not authorized to use this resource.</p>";
		}
	}
?>